package com.quan.mobile.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.quan.common.core.BaseController;
import com.quan.weixin.entity.WeixinOauthUser;
import com.quan.weixin.service.WeixinOauthUserService;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@RestController
@RequestMapping("/weixin/oauth")
public class WeixinOauthController extends BaseController {

	@Autowired
	private WxMpService wxMpService;

	@Autowired
	private WeixinOauthUserService weixinOauthUserService;

	// 微信授权回调地址
	private String callbackUrl = "http://yhaoquan.imwork.net/weixin/oauth/oauth_callback_userinfo";
	// 授权后跳转的业务页面URL
	private String bizPageUel = "http://yhaoquan-wx.wicp.net";

	/**
	 * 网页授权，获取用户详细信息，需要用户授权
	 * 
	 * @param state
	 */
	@GetMapping(value = "/oauth_process_userinfo")
	public void oAuthProcessUserInfo(String state) {
		logger.debug("-----------------------微信网页授权，引导用户到授权页面----------------------------");

		try {
			String getCodeUrl = this.wxMpService.oauth2buildAuthorizationUrl(callbackUrl, WxConsts.OAuth2Scope.SNSAPI_USERINFO, bizPageUel);
			this.response.sendRedirect(getCodeUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 网页授权回调处理方法
	 * 
	 * @return
	 */
	@GetMapping(value = "/oauth_callback_userinfo")
	public void OAuthCallbackUserInfo() {
		logger.debug("-----------------------微信网页授权，回调处理----------------------------");

		try {
			// 接收微信传回的code参数
			String code = request.getParameter("code");
			// 接收用户从微信客户端传来的参数（比如用户传的是一个业务URL页面地址，处理完以下业务后直接跳转到该业务URL地址）
			String state = request.getParameter("state");

			WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);

			WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);

			WeixinOauthUser oauthUser = this.weixinOauthUserService.getUserByOpenId(wxMpUser.getOpenId());
			if (null == oauthUser) {
				// 将授权用户存储到数据库
				WeixinOauthUser user = new WeixinOauthUser();
				user.setOpenid(wxMpUser.getOpenId());
				user.setHeadimgurl(wxMpUser.getHeadImgUrl());
				user.setNickname(wxMpUser.getNickname());
				user.setSex(wxMpUser.getSex());
				user.setCity(wxMpUser.getCity());
				user.setCountry(wxMpUser.getCountry());
				this.weixinOauthUserService.insertSelective(user);
			}

			String toUrl = state + "?openid=" + wxMpUser.getOpenId();
			this.response.sendRedirect(toUrl);

			logger.debug("用户信息：{}", wxMpUser.toString());
			logger.debug("跳转地址：{}", toUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
